package com.athuahua.spzx.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.athuahua.spzx.vo.system.ValidateCodeVo;
import com.athuahua.spzx.service.ValidateService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: huahua
 * @Date: 2024/7/21 0021
 * @Time: 18:48
 * @Description:
 */
@Service
public class ValidateServiceImpl implements ValidateService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1.通过工具生成图片验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String code = circleCaptcha.getCode();//4位验证码的值
        String imageBase64 = circleCaptcha.getImageBase64();//返回图片验证码 base64编码方式
        //2.验证码存储到redis中
        String key = UUID.randomUUID().toString().replaceAll("-","");

        redisTemplate.opsForValue().set(
                "user:validate" + key,
                code,
                5,
                TimeUnit.MINUTES
        );
        //3.返回对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);

        //表示是一个图片类型的验证码
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);


        return validateCodeVo;
    }
}
